$(function() {
	/* 项目路径 */
	var baseURL = /knowledge/
	/* 构建列表 */
	$("#jqGrid").jqGrid(
					{
						url : baseURL + '/document/knowledgeReview/wdfb',
						datatype : "json",
						colModel : [
								{
									label : '编号',
									name : 'documentId',
									index : "documentOrigin",
									width : 20,
									key : true
								},
								{
									label : '来源',
									name : 'documentOrigin',
									index : "documentOrigin",
									width : 45
								},
								{
									label : '作者',
									name : 'documentAuthor',
									width : 35
								},
								{
									label : '时间',
									name : 'documentUploadDate',
									width : 90
								},
								{
									label : '摘要',
									name : 'documentAbstract',
									width : 100
								},
								/*{
									label : '审批状态',
									name : 'documentState',
									width : 35,
									formatter : function(value, options, row) {

										if (value == 0) {
											return '<span class="label label-info">等待审核</span>';
										}
										if (value == 1) {
											return '<span class="label label-success">审核通过</span>';
										}
										if (value == 2) {
											return '<span class="label label-danger">审核不过</span>';
										}
									}
								},*/
								{label : '标签',name : 'lableInfos',width : 100,
									formatter : function(value, options, row) {
										debugger
										var lableName="";
					                    for (var i = 0; i < value.length; i++) {
					                    	lableName+=value[i].lableName+",";
					                    }
										return lableName;
									}
								},
								{
									label : '文档',
									name : 'files',
									width : 100,
									formatter : function(value, options, row) {
										debugger
										var spanItem = '<div >'
						                    for (var i = 0; i < value.length; i++) {
						                        debugger
												console.log(value[i].documentSaveurl)
												var url = value[i].documentSaveurl
												
												var inputFile=url
												var newUrl = url.replace(/\\/g,"\/");
												var realUrl = baseURL + "localFile"+ newUrl.substr(12)
												var aItm=null;
												var index = realUrl.lastIndexOf(".");
												var ext = realUrl.substr(index+1).toLowerCase();
												var fileName=inputFile.split("\\")[3].substr(15)
												realUrl = encodeURI(realUrl)
												
												inputFile=encodeURI(inputFile)
												if(ext=="pdf"){
													aItm = "<a class='label label-info'  style='display:block;margin:2px;'  target='_blank' href="+ realUrl + " title="+fileName+" >"+fileName+" </a>"
												}else{
													aItm = "<a class='label label-info' style='display:block;margin:2px;' documentId="+row.documentId+" inputFile="+inputFile+" id='officetopdf' title="+fileName+" >"+fileName+"</a>"
												}
												spanItem += aItm
						                    }
					                    spanItem + '</div>'
										return spanItem;
									}
								} ],
						viewrecords : true,
						height : 385,
						rowNum : 10,
						rowList : [ 10, 30, 50 ],
						rownumbers : true,
						rownumWidth : 25,
						autowidth : true,
						multiselect : true,
						pager : "#jqGridPager",
						jsonReader : {
							root : "page.list",
							page : "page.pageNum",
							total : "page.pages",
							records : "page.total"
						},
						prmNames : {
							page : "page",
							rows : "limit",
							order : "order"
						},
						gridComplete : function() {
							// 隐藏grid底部滚动条
							$("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x" : "hidden"});
							
				            //修改样式 start ==========================
				            var divs=$("td").filter("[role=gridcell]").find("div")
				            for(var i=0;i<divs.length;i++){
				            	//console.log("itmes: "+divs[i].childElementCount)
				            	lineCount=divs[i].childElementCount;
				            	if(lineCount>1){
				            		var tds=$(divs[i].parentElement.parentElement).find("td")
				            		for(var j=0;j<tds.length-1;j++){
				            			debugger
				            			$(tds[j]).css({"padding-top":""+lineCount+"0px"})
				            		}
				            	}
				            }
				            //修改样式 end ==========================
						}
					});
    $(document).on("click","a[id='officetopdf']",function(){
    	var athis=$(this)
    	var documentId=parseInt(athis.attr("documentId"))
    	var inputFile=athis.attr("inputFile")
    	var url=baseURL+"lookdocument/officeToPdf"
    	debugger
    	var data={"inputFile":inputFile,"documentId":documentId}
    	var newwindow=window.open("about:blank");
    	$.post(url,data,function(r){
    		debugger;
    		console.log(r)
    		var url=r.url
    		var newUrl = url.replace(/\\/g,"\/");
			var realUrl = baseURL + "localFile"+ newUrl.substr(17)
			newwindow.location.href=realUrl;
            newwindow.focus();
    	});
    })
})



var deptZtree;
var deptSetting = {
	data: {
		simpleData: {
			enable: true,
			idKey: "deptid",
			pIdKey: "preid",
			rootPId: "-1"
		}
	},
	callback: {
		beforeClick: function(treeId, treeNode) {
			deptZtree = $.fn.zTree.init($("#deptTree"),deptSetting, zNodes);
			//展开所有节点
			deptZtree.expandAll(true);
		}
	},
	check: {
        enable: true,
        //chkStyle: "radio",  //单选框
        chkStyle: "checkbox",  //单选框
        radioType: "all"   //对所有节点设置单选
    }
};

var userZtree;
var userSetting = {
		data: {
			simpleData: {
				enable: true,
				idKey: "userid",
				pIdKey: "preid",
				rootPId: "-1"
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {
			    userZtree = $.fn.zTree.init($("#userTree"),userSetting, zNodes);
				//展开所有节点
				userZtree.expandAll(true);
			}
		},
		check: {
			enable: true,
			//chkStyle: "radio",  //单选框
			chkStyle: "checkbox",  //单选框
			radioType: "all"   //对所有节点设置单选
		}
};


var vm = new Vue({
	el : '#rrapp',
	data : {
		q : {
			key : null
		},
		showList : true,
		showUserList:true,
		showDeptList:true,
		title : null,
		document : {
			documentUploadDate : null,
			documentAbstract : null,
			documentId : null,
		},
		userList : [],
		deptList : [],
		user:{},
		dept:{},
		userSelected : null,
		deptSelected : null
	},
	methods : {
		query : function() {
			if (vm.q.userName == null) {
				alert("查询条件不能为空!");
				return false;
			}
			vm.reload();
		},
		reload : function() {
			vm.showList = true;
			vm.showUserList=true;
			vm.showDeptList=true;
			var page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
				postData : {
					'userName' : vm.q.userName
				},
				page : page
			}).trigger("reloadGrid");
		},
		preReleaseToDept : function() {
			var documentId = getSelectedRow();
			if (documentId == null) {
				return;
			}
			vm.showList = false;
			vm.showDeptList = false;
			vm.showUserList = true;
			vm.title = "文档发布";
			// 获取角色信息
			//this.getUserAndDept();
			vm.document.documentId=documentId
			//vm.hello()
			vm.getDetpMap()
		},
		preReleaseToUser : function() {
			var documentId = getSelectedRow();
			if (documentId == null) {
				return;
			}
			vm.showList = false;
			vm.showDeptList = true;
			vm.showUserList = false;
			vm.title = "文档发布";
			// 获取角色信息
			vm.document.documentId=documentId
			vm.getUserMap()
		},
		userRelease:function(){
			var userTreeObj = $.fn.zTree.getZTreeObj("userTree");
            var userNodes = userTreeObj.getCheckedNodes(true);
			
            debugger
			console.log("vm.document.documentId   :"+vm.document.documentId)
			if (userNodes.length==0) {
				alert("发布人不能为空");
				return true;
			}
			var msg = null;
			
			var userArray=[]
			if (userNodes.length>0) {
				for(var j=0;j<userNodes.length;j++){
					var user={}
					user.userid=userNodes[j].userid
					user.username=userNodes[j].name
					userArray.push(user)
				}
				msg = "确定发布么？";
				var userdept={}
				userdept.userArray=userArray;
				userdept.documentId=vm.document.documentId
				//
				vm.commonRelease(msg,userdept);
			}
		},
		deptRelease : function() {
			var deptTreeObj = $.fn.zTree.getZTreeObj("deptTree");
            var deptNodes = deptTreeObj.getCheckedNodes(true);
			debugger
			console.log("vm.document.documentId   :"+vm.document.documentId)
			if (deptNodes.length==0) {
				alert("发布部门不能为空");
				return true;
			}
			var msg = null;
			var deptArray=[]
			if (deptNodes.length>0) {
				for(var i=0;i<deptNodes.length;i++){
					var department={}
					department.deptid=deptNodes[i].deptid
					department.deptname=deptNodes[i].name
					deptArray.push(department)
				}
				msg = "确定发布么？";
				var userdept={}
				userdept.deptArray=deptArray;
				userdept.documentId=vm.document.documentId;
				
				//
				vm.commonRelease(msg,userdept);
			}
		},
		commonRelease:function(msg,userdept){
			confirm(msg, function() {
				$.ajax({
					type : "POST",
					url : baseURL + "/document/documentRelease",
					dataType : "json",
					contentType : "application/json",
					data : JSON.stringify(userdept),
					success : function(result) {
						debugger
						if (result.code == 500) {
							alert(result.msg);
						} else {
							alert("发布成功!");
						}
						vm.deptSelected = null;
						vm.userSelected = null;
						vm.reload();
					}
				});
			});
		},
		getUserAndDept : function() {
			$.get(baseURL + "document/getUserAndDept", function(r) {
				vm.userList = r.userDept.userList
				vm.deptList = r.userDept.deptList
				debugger
			});
		},
		passOrFalse : function() {
			if (event) {
				var status = event.target.getAttribute("status")
				debugger
			}
			var msg = ""
			if (status == 1) {
				msg = '确定要审核通过？'
			} else {
				msg = '确定要审核不过？'
			}
			confirm(msg, function() {
				$.post(baseURL + "/document/passOrfailService", {
					"documentid" : vm.document.documentId,
					"status" : status
				}, function(result) {
					alert("操作成功");
					vm.reload();
				});
			});
		},
		getDetpMap:function(){//部门tree
			$.get(baseURL + "document/getDeptUserMap", function(r) {
				console.log(r.deptMap)
				var zDiv = $("#deptTree")
	             ztree = $.fn.zTree.init(zDiv, deptSetting, r.deptMap);
	             //展开所有节点
				ztree.expandAll(true);
				debugger
				if (vm.document.documentId != null) {
					vm.queryDeptIdListByDocumentId()
				}
			});
		},
		getUserMap:function(){//部门tree
			$.get(baseURL + "document/getDeptUserMap", function(r) {
				console.log(r.userMap)
				var zDiv = $("#userTree");
				ztree = $.fn.zTree.init(zDiv, userSetting, r.userMap);
				//展开所有节点
				ztree.expandAll(true);
				debugger
				if (vm.document.documentId != null) {
					vm.queryUserIdListByDocumentId()
				}				
			});
		},
		queryDeptIdListByDocumentId:function(){//部门id
			$.get(baseURL + "document/getDeptOrUserIdListByDocumentId", {"documentId":vm.document.documentId},function(r) {
				vm.dept.deptIdList=r.deptIdList
				
				//勾选角色所拥有的菜单
    			var depts = vm.dept.deptIdList;
    			for(var i=0; i<depts.length; i++) {
    				var node = ztree.getNodeByParam("deptid", depts[i]);
    				ztree.checkNode(node, true, false);
    			}
			});
		},
		queryUserIdListByDocumentId:function(){//用户id
			$.get(baseURL + "document/getDeptOrUserIdListByDocumentId", {"documentId":vm.document.documentId},function(r) {
				vm.user.userIdList=r.userIdList
				//勾选角色所拥有的菜单
    			var users = vm.user.userIdList;
    			for(var i=0; i<users.length; i++) {
    				var node = ztree.getNodeByParam("userid", users[i]);
    				ztree.checkNode(node, true, false);
    			}
			});
		}
	}
});